<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userId">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入用户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择账户状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['account:account:add']"
        >开户</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-money"
          size="mini"
          :disabled="single"
          @click="handleRecharge"
          v-hasPermi="['account:account:recharge']"
        >充值
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleCardList"
          v-hasPermi="['account:account:remove']"
        >开卡
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleFreeze"
          v-hasPermi="['account:account:remove']"
        >冻结
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleUnfreeze"
          v-hasPermi="['account:account:remove']"
        >解冻
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCancel"
          v-hasPermi="['account:account:remove']"
        >注销
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['account:account:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['account:account:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="账户编号" align="center" prop="id"/>
      <el-table-column label="人员" align="center" prop="userName"/>
      <el-table-column label="电话" align="center" prop="phonenumber"/>
      <el-table-column label="账户状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="余额（元）" align="center" prop="balance"/>
      <el-table-column label="押金（元）" align="center" prop="deposit"/>
      <el-table-column label="管理费（元）" align="center" prop="addfare"/>
      <el-table-column label="有效期" align="center" prop="avdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.avdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['account:account:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="人员" prop="userId">
          <el-input v-model="form.userName" placeholder="请输入用户" readonly/>
        </el-form-item>
        <el-form-item label="余额（元）" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额"/>
        </el-form-item>
        <el-form-item label="押金（元）" prop="deposit">
          <el-select v-model="form.deposit">
            <el-option
              v-for="dict in depositOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理费（元）" prop="addfare">
          <el-select v-model="form.addfare">
            <el-option
              v-for="dict in addfareOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="avdate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.avdate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-select v-model="form.status">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 充值对话框 -->
    <el-dialog :title="title" :visible.sync="rechargeOpen" width="500px" append-to-body>
      <el-form ref="rechargeform" :model="rechargeData" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userName">
          <el-input v-model="rechargeData.userName" placeholder="请输入用户" readonly/>
        </el-form-item>
        <el-form-item label="当前余额" prop="balance">
          <el-input v-model="rechargeData.balance" readonly/>
        </el-form-item>
        <el-form-item label="充值金额（元）" prop="amount">
          <el-radio-group v-model="rechargeData.amount">
            <el-radio
              v-for="dict in addMoneyOptions" :key="dict.dictValue" :label="parseInt(dict.dictValue)">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付渠道" prop="channelCode">
          <el-select v-model="rechargeData.channelCode">
            <el-option
              v-for="dict in payChannelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRechargeForm">确 定</el-button>
        <el-button @click="cancelRecharge">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAccount,
    getAccount,
    delAccount,
    addAccount,
    updateAccount,
    exportAccount,
    freezeAccount,
    unfreezeAccount,
    cancelAccount,
    recharge
  } from "@/api/account/account";

  export default {
    name: "Account",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 账户表格数据
        accountList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 账户状态：0，正常，1冻结，2注销字典
        statusOptions: [],
        //押金
        depositOptions: [],
        //管理费
        addfareOptions: [],
        //有效期
        avdateOptions: [],
        //增款金额
        addMoneyOptions: [],
        //支付渠道
        parChannelOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: null,
          status: null,
          phonenumber:null,
          userName:null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userId: [{
            required: true,
            message: '请输入单行文本',
            trigger: 'blur'
          }],
          amount: [{
            required: true,
            message: '请输入金额',
            trigger: 'blur'
          }],
        },
        //充值弹出框
        rechargeOpen: false,
        //充值参数
        rechargeData: {
          userName: "",
          id: "",
          balance: "",
          amount: "",
          channelCode: ""
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("card_account_status").then(response => {
        this.statusOptions = response.data;
      });
      //押金字典
      this.getDicts("acc_account_deposit").then(response => {
        this.depositOptions = response.data;
      });
      //管理费字典
      this.getDicts("acc_account_addfare").then(response => {
        this.addfareOptions = response.data;
      });
      //有效期字典
      this.getDicts("acc_account_avdate").then(response => {
        this.avdateOptions = response.data;
      });
      //增款金额字典
      this.getDicts("money_amount").then(response => {
        this.addMoneyOptions = response.data;
      });
      //支付渠道
      this.getDicts("pay_channel").then(response => {
        this.payChannelOptions = response.data;
        this.rechargeData.channelCode = response.data[0].id;
      });
    },
    methods: {
      /** 查询账户列表 */
      getList() {
        this.loading = true;
        listAccount(this.queryParams).then(response => {
          this.accountList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 账户状态：0，正常，1冻结，2注销字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userId: null,
          userName: null,
          balance: null,
          deposit: null,
          addfare: null,
          avdate: null,
          status: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remarks: null,
          delFlag: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加账户";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getAccount(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改账户";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateAccount(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addAccount(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除账户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delAccount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有账户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportAccount(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 冻结按钮操作 */
      handleFreeze(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认冻结（冻结后将不能使用）账户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return freezeAccount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("冻结成功");
        })
      },
      /** 解冻按钮操作 */
      handleUnfreeze(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认解冻账户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return unfreezeAccount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("解冻成功");
        })
      },
      /** 注销按钮操作 */
      handleCancel(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认注销（注销后将不能使用和恢复）账户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return cancelAccount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("注销成功");
        })
      },

      /** 充值按钮操作 */
      handleRecharge(row) {
        var that = this;
        const id = row.id || this.ids;
        getAccount(id).then(response => {
          that.rechargeData = {"id": id, "userName": response.data.userName, "balance": response.data.balance};
          that.rechargeOpen = true;
          that.title = "充值";
        });


      },
      // 取消充值按钮
      cancelRecharge() {
        this.rechargeOpen = false;
        this.resetRechargeForm();
      },
      // 充值表单重置
      resetRechargeForm() {
        this.rechargeform = {
          id: null,
          userName: null,
          balance: null
        };
        this.resetForm("rechargeForm");
      },
      //
      /** 提交充值按钮 */
      submitRechargeForm() {
        var source = "4";
        recharge(this.rechargeData.id, this.rechargeData.amount, source, this.rechargeData.channelCode).then(response => {
          this.msgSuccess("充值成功");
          this.rechargeOpen = false;
          this.getList();
        });
      },
      handleCardList(row) {
        const id = row.id || this.ids;
          let routeUrl = this.$router.resolve({
            path: "/account/card",
            query: {"accountId":id}
          });
          window.open(routeUrl.href, '_self');
      },
    }
  };
</script>
